<?php
class AdminPostsController extends AppController {
	
	//set name of the layout
	public $layout='admin';
	
	public $helpers = array (
			'Html',
			'Form',
			'Session'
	);

	public function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('profile');
	}
	
	public function index($userId = null) {
		if(!$userId) {
			return $this->render('/errors/error');
		}
		
		//initiate session check authority
		$this->Session->write('author', false);
		
		//call method check login
		$checkLogin = $this->checkLogin();
		
		
		//check authority
		if(is_array($checkLogin)) {
			if($userId == $checkLogin['loginId']) {
				//user has full authority on profile.ctp
				$this->Session->write('author', true);
			}
		}
		
		$this->loadModel('Post');
		$allPost = $this->Post->find ( 'all', array (
				'conditions' => array (
						'Post.user_id' => $checkLogin ['loginId']
				)) );
		//set data for profile.ctp
		$this->set('allCreatedPosts', $allPost);
		
		
	}
	
	/**
	 * Method transit to profile.ctp
	 */
	public function profile($userId = null) {
		//check parameter
		if(!$userId) {
			return $this->render('/errors/error');
		}
		
		//initiate variable check authority
		$isAuthor = 0;
		
		//call method check login
		$checkLogin = $this->checkLogin();
		
		//check authority
		
		if(is_array($checkLogin)) {
			if($userId == $checkLogin['loginId']) {
				//user has full authority on profile.ctp
				$isAuthor=1;
			}
		}
		
		$this->loadModel('User');
		//set data for profile.ctp
		$this->set('user', $this->User->findByid($userId));
		$this->loadModel('Post');
		$this->set('created', $this->Post->findAllCreatedPost($userId));
// 		$allPost = $this->Post->find ( 'all', array (
// 				'conditions' => array (
// 						'Post.user_id' => $userId
// 				)) );
		
// 		foreach ($allPost as $key => $post){
// 			$bodytext = $post['Post']['body'];
// 			$bodyS = $this->reviewText ( 100, $bodytext );
// 			$allPost[$key]['Post']['body'] = $bodyS;
// 		}
		
		//set data for profile.ctp		
		$this->set('isAuthor',$isAuthor);
// 		$this->set('allCreatedPosts', $allPost);
		$this->set('posts', $this->getAllDataPaging($userId));
		$this->set('chartData', $this->getChartData($userId));
	}

	/**
	 * Method add post
	 */
	public function add() {
		//check login
		$checkLogin = $this->checkLogin();
		if(!$checkLogin) {
			return $this->render('/errors/error');
		}
		$this->loadModel('Post');
		$this->loadModel('User');
		// save to db
		if ($this->request->is( 'post' )) {
			
			
			$this->Post->create();
			if ($this->Post->save ( $this->request->data )) {
				
				// search id for redirect to view.ctp
				$newPost = $this->Post->find ( 'first', array (
						'conditions' => array (
								'Post.user_id' => $checkLogin ['loginId']
						),
						'order' => 'Post.modified DESC'
				) );
				
				
				$this->Session->setFlash ( 'Your post has been saved', 'default', array (
						'class' => 'alert alert-success'
				) );
	
				return $this->redirect ( array (
						'controller' => 'posts',
						'action' => 'detail',
						$newPost ['Post'] ['id'],
						'?' => array (
								'b' => 'm'//flag for backDestination
						)
				) );
			}
			$this->Session->setFlash ( 'Unable to save your post', 'default', array (
					'class' => 'alert alert-danger'
			) );
			
		}
	}
	private function upload() {
		/* form submitted? */
		if ($this->request->is('post')) {
			$filename = "app/webroot/files/".$this->data['thumbnail']['name']; 
           /* copy uploaded file */
			if (move_uploaded_file($this->data['thumbnail']['tmp_name'],$filename)) {
				/* save message to session */
				//$this->Session->setFlash('File uploaded successfuly. You can view it <a href="/app/webroot/files/'.$this->data['Pages']['file']['name'].'">here</a>.');
				/* redirect */
				//$this->redirect(array('action' => 'index'));
			} else {
				/* save message to session */
				//$this->Session->setFlash('There was a problem uploading file. Please try again.');
			}
		}
		//$this->render('home');
	}
	
	/**
	 * Method edit post
	 */
	public function edit($id = null) {
		//check login
		$checkLogin = $this->checkLogin();
		if(!$checkLogin) {
			return $this->render('/errors/error');
		}
		
		// check params
		if (!$id) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}

		//Load model Post
		$this->loadModel('Post');

		
		$post = $this->Post->findById ( $id );
		if (! $post) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}
	
		// check is Author tanthm
		if(is_array($checkLogin)) {
			if($post['Post']['user_id'] !== $checkLogin['loginId']) {
				return $this->render('/errors/error');
			}
		}
		
		
		// save to db
		if ($this->request->is ( 'post' ) || $this->request->is ( 'put' )) {
			if($post['Post']['user_id'] == $checkLogin['loginId']) {
				$this->Post->id = $id;
				if ($this->Post->save ( $this->request->data )) {
					$this->Session->setFlash ( 'Your post has been updated', 'default', array (
							'class' => 'alert alert-success'
					) );
					return $this->redirect ( array (
							'controller' => 'posts',
							'action' => 'detail',
							$id
					) );
				}
			}
			$this->Session->setFlash ( 'Unable to update your post', 'default', array (
					'class' => 'alert alert-danger'
			) );
		}
		// initialize value if update date is not available
		if (! $this->request->data) {
			$this->request->data = $post;
		}
		// reder view layout for edit
		$this->set ( 'post', $post );
	}
	
	/**
	 * Method delete post
	 */
	public function delete($id = null) {
		//check login
		$checkLogin = $this->checkLogin();
		if(!$checkLogin) {
			return $this->render('/errors/error');
		}
	
		// check request method, if not 'Post' throw error
		if ($this->request->is ( 'get' )) {
			throw new MethodNotAllowedException ();
		}
	
		// delete data in db, cascade setting help delete depedent child data
		$this->loadModel('Post');
		
		// check is Author tanthm
		if(is_array($checkLogin)) {
			if($post['Post']['user_id'] !== $checkLogin['loginId']) {
				return $this->render('/errors/error');
			}
		}
		
		if ($this->Post->delete ( $id )) {
			$this->Session->setFlash ( 'Deleted', 'default', array (
					'class' => 'alert alert-success'
			) );
			return $this->redirect ( array (
					'controller' => 'adminposts',
					'action' => 'profile',
					$checkLogin['loginId']
			) );
		}
	}
	
	/**
	 * Method search for admin
	 */
	public function search() {
		
	}
	
	/**
	 * Method escape special symbols
	 */
	private function escape($str = null) {
		if(!$str) {
			return $this->render('/errors/error');
		}
		return $this->render('/adminposts/profile/1');
	}
	
	/**
	 * Method check login
	 */
	private function checkLogin() {
// 		if (1==1){
// 			$this->loadModel('User');
// 			$temp['User']['id'] = 1;
// 			$this->Session->write("UserLogin", $temp);
// 			return array(true,'loginId' => '1');
// 		}
		if($this->Auth->user()) {
			$user = $this->Auth->user();
			return array(true,'loginId' => $user['id']);
		}
		return false;
	}
	
	/**
	 * Method check whether user exists
	 */
	private function checkUserExist($userId = null) {
		$check = $this->Admin->find('all',array('conditions' => array('Admin.AdminID' => $id)));
		if(!$check) {
			return $this->render('/errors/error');
		}
	}
	
	/**
	 * Method get paging
	 */
	private function getAllDataPaging($userId = null) {
		$this->paginate = array(
				'conditions' => array('Post.user_id' => $userId),
				'limit' => 5,
				'order' => 'Post.modified DESC'
		);
		try {
			return $this->paginate ( 'Post' );
		} catch ( NotFoundException $e ) {
			return $this->render('/errors/error');
		}
	}
	
	/**
	 * Method get data for chart
	 */
	private function getChartData($userId = null) {
		// find all the date this user create post, group by created date
		$results = $this->Post->find ( 'all', array (
				'conditions' => array (
						'Post.user_id' => $userId
				),
				'fields' => array (
						'DATE(Post.created) AS created',
						'COUNT(*) AS quantity'
				),
				'group' => array (
						'DATE(Post.created)'
				),
				'order' => array (
						'DATE(Post.created) ASC'
				)
		) );
	
		// group the result again, this time by month_year
		$monthYearGroup = array ();
		App::uses ( 'CakeTime', 'Utility' );
		$dummyStr = "";
		$tempCount = 0;
	
		for($i = 0; $i < sizeof ( $results ); $i ++) {
			$rTime = CakeTime::format ( $results [$i] [0] ['created'], '%B_%Y' );
	
			//check whether the value month_year is stored in $monthYearGroup array, use another temp string
			if (strpos ( $dummyStr, $rTime ) === false) {
				$dummyStr = $dummyStr . $rTime . ' ';
	
				// sum the quantity of equal-month_year records
				for($j = $i; $j < sizeof ( $results ); $j ++) {
					$rTimeChild = CakeTime::format ( $results [$j] [0] ['created'], '%B_%Y' );
	
					if ($rTimeChild == $rTime) {
						$tempCount = $tempCount + $results [$j] [0] ['quantity'];
					} else {
						break;
					}
				}
	
				// store the new month_year time and quantity into array
				array_push ( $monthYearGroup, array (
				'dateTime' => $rTime,
				'quantity' => $tempCount
				) );
				$tempCount = 0;
			}
		}
	
		//json encode for data chart
		$chartData ['cols'] = array (
				array (
						'id' => 'created',
						'label' => 'Date',
						'type' => 'string'
				),
				array (
						'id' => 'quantity',
						'label' => 'Posted',
						'type' => 'number'
				)
		);
		foreach ( $monthYearGroup as $result ) {
			// $time = strtotime ( $result [0] ['created'] );
			// $dateJs = 'Date(' . date ( "Y", $time ) . ', ' . (date ( 'n', $time ) - 1) . ', ' . date ( 'j', $time ) . ')';
			$row = array (
					'c' => array (
							array (
									'v' => $result ['dateTime']
							),
							array (
									'v' => $result ['quantity']
							)
					)
			);
			$chartData ['rows'] [] = $row;
		}
		return json_encode ( $chartData ) ;
	}
// 	private function reviewText($maxLength, $html) {
// 		if (! $html)
// 			return "";
// 		// remove all tag html - ThanhLD1
// 		$result = trim ( strip_tags ( $html ) );
// 		if (empty ( $result )) {
// 			$result = "<p style=\"color: red;\">SORRY! NO REVIEW TEXT!</p>";
// 		}
// 		// cut string with length is maxLength - ThanhLD1
// 		if (strlen ( $result ) > $maxLength) {
// 			$pos = strpos($result, ' ', $maxLength);
// 			$result = substr ( $result, 0, $pos );
// 			$result .= "....";
// 		}
	
// 		return $result;
// 	}
}